//
//  LoginMainViewController.m
//  BanBanApp
//
//  Created by 时伟平 on 16/7/4.
//  Copyright © 2016年 时伟平. All rights reserved.
//

#import "LoginMainViewController.h"
#import "HYBImageCliped.h"
#import "BXTabBarController.h"
#import "LeftViewController.h"
#import "RootViewController.h"

#import "EnrollMainViewController.h"
#import "NoCompanyViewController.h"


#import "RetrievePasswordViewController.h"


#import "UserManager.h"

// 发送验证码
#define SendCode @""BanBanBaoAPI@"/registorlogin/sendCode"
// 登录
#define UserLogin @""BanBanBaoAPI@"/ofclogin/login"
@interface LoginMainViewController ()
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic,assign)NSInteger count;
@end

@implementation LoginMainViewController{
    UIImageView *topView;
    UIButton *loginBtn;
    UIButton *forgetCodeBtn;
    UIButton *registerNowBtn;
    UIButton *switchLogin;//切换登录方式
    BOOL isCodeLogin;//是否验证码登录
}

- (void)viewDidLoad {
    [super viewDidLoad];
      // Do any additional setup after loading the view.
    _count = 60;
    [self addContentView];
    
}

-(void)addContentView{
    
    isCodeLogin = NO;
    
    topView = [[UIImageView alloc]init];
    topView.image = [UIImage imageNamed:@"背景图-750_430"];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(FitRealW(245));
    }];
    
    self.UserAccountTF = [UITextField textFieldWithPlaceholder:@"请输入手机号" imageName:@"user"];
    _UserAccountTF.text = @"18521376312";
    [self.view addSubview:_UserAccountTF];
    _UserAccountTF.keyboardType = UIKeyboardTypeNumberPad;
    [_UserAccountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(FitRealW(31));
        make.right.mas_equalTo(FitRealW(-15));
        make.top.equalTo(topView.mas_bottom).offset(FitRealW(10));
    }];
    
   
    self.UserPasswordTF = [UITextField textFieldWithPlaceholder:@"输入密码" imageName:@"lock"];
    _UserPasswordTF.text = @"1234567";
    _UserPasswordTF.secureTextEntry = YES;
    [self.view addSubview:_UserPasswordTF];
    [_UserPasswordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(FitRealW(31));
        make.right.mas_equalTo(FitRealW(-105));
        make.top.equalTo(_UserAccountTF.mas_bottom).offset(FitRealW(10));
    }];
  
   
    forgetCodeBtn = [UIButton buttonWithTitle:@"忘记密码?" titleColor:UIColorFromRGB(0x3F81EC) font:[UIFont systemFontOfSize:12] target:self action:@selector(didForgetCodeBtn)];
    [self.view addSubview:forgetCodeBtn];
    [forgetCodeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(_UserPasswordTF.mas_height);
        make.right.mas_equalTo(FitRealW(-15));
        make.left.mas_equalTo(_UserPasswordTF.mas_right).offset(FitRealW(5));
        make.top.mas_equalTo(_UserAccountTF.mas_bottom).offset(FitRealW(10));
    }];
    
    
    
    loginBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [loginBtn setTitle:@"登录" forState:(UIControlStateNormal)];
    [loginBtn setBackgroundColor:UIColorFromRGB(0x3F81EC)];
    [self.view addSubview:loginBtn];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(FitRealW(40));
        make.right.mas_equalTo(FitRealW(-20));
        make.left.mas_equalTo(FitRealW(20));
        make.top.mas_equalTo(_UserPasswordTF.mas_bottom).offset(FitRealW(30));
    }];
    [loginBtn addTarget:self action:@selector(didLoginBtn) forControlEvents:(UIControlEventTouchUpInside)];
    //圆角设置
   loginBtn.hyb_borderWidth = 1;
   loginBtn.hyb_borderColor = [UIColor clearColor];
   [loginBtn hyb_addCornerRadius:FitRealW(5)];
    
    
    switchLogin = [UIButton buttonWithTitle:@"验证码登录" titleColor:UIColorFromRGB(0x3F81EC) font:[UIFont systemFontOfSize:12] target:self action:@selector(didSwitchLogin:)];
    [self.view addSubview:switchLogin];
    [switchLogin mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(FitRealW(80), FitRealW(30)));
        make.right.equalTo(forgetCodeBtn.mas_right);
        make.top.equalTo(loginBtn.mas_bottom).offset(FitRealW(10));
    }];
    
    
    
    UILabel *noAccount = [UILabel labelWithTitle:@"没有账号?" color:[UIColor grayColor] font:[UIFont systemFontOfSize:12] alignment:NSTextAlignmentRight];
    [self.view addSubview:noAccount];
    [noAccount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(FitRealW(80), FitRealW(30)));
        make.centerX.offset(FitRealW(-35));
        make.bottom.mas_equalTo(FitRealW(-20));
    }];
   
  
    registerNowBtn = [UIButton buttonWithTitle:@"立即注册" titleColor:UIColorFromRGB(0x3F81EC) font:[UIFont systemFontOfSize:12] target:self action:@selector(didregisterNowBtn)];
    [self.view addSubview:registerNowBtn];
    [registerNowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(FitRealW(80), FitRealW(30)));
        make.left.equalTo(noAccount.mas_right).offset(0);
        make.bottom.mas_equalTo(FitRealW(-20));
    
    }];

 
        UIImageView *line = [[UIImageView alloc]init];
        line.image = [UIImage imageNamed:@"Line"];
        [self.view addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(1);
            make.right.mas_equalTo(FitRealW(-20));
            make.left.mas_equalTo(FitRealW(20));
            make.top.mas_equalTo(_UserAccountTF.mas_bottom).offset(FitRealW(5));
        }];
  
   
    UIImageView *line1 = [[UIImageView alloc]init];
    line1.image = [UIImage imageNamed:@"Line"];
    [self.view addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(1);
        make.right.mas_equalTo(FitRealW(-20));
        make.left.mas_equalTo(FitRealW(20));
        make.top.mas_equalTo(_UserPasswordTF.mas_bottom).offset(FitRealW(5));
    }];
  
    
}

/**
 *  验证码倒计时
 */
-(void)timeChangeNum{
    
    if (_count == 0) {
        [_timer invalidate];
        _timer = nil;
        [forgetCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
       forgetCodeBtn.enabled = YES;
        _count = 60;
        return;
    }
    [forgetCodeBtn setTitle:[NSString stringWithFormat:@"%lds",_count--] forState:UIControlStateNormal];
}

/**
 *  切换登录方式
 */
-(void)didSwitchLogin:(UIButton *)btn{
    btn.selected = !btn.selected;
    isCodeLogin = btn.selected;
    [self changerLogeType:isCodeLogin];
}
-(void)changerLogeType:(BOOL)type{
    if (type) {
        self.UserPasswordTF.placeholder = @"输入验证码";
        [switchLogin setTitle:@"验证码登录" forState:UIControlStateNormal];
        [forgetCodeBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
    }else{
        self.UserPasswordTF.placeholder = @"输入密码";
        [switchLogin setTitle:@"密码登录" forState:UIControlStateNormal];
        [forgetCodeBtn setTitle:@"忘记密码?" forState:UIControlStateNormal];
    }
    
}

/**
 *  忘记密码
 */
-(void)didForgetCodeBtn{
    
    if (isCodeLogin) {
        //发送验证码
        [self getCode];
    }else{
        //忘记密码
        RetrievePasswordViewController *retirePasswordVC = [[RetrievePasswordViewController alloc]init];
        [self.navigationController pushViewController:retirePasswordVC animated:YES];
    }
}
/**
 *  登录
 */
-(void)didLoginBtn{
  
   
//[self loginSuccess];
    
[self userCodeLoginWith:[NSString stringWithFormat:@"%@",isCodeLogin?@"2":@"1"]];
}
/**
 *  立即注册
 */
-(void)didregisterNowBtn{
    EnrollMainViewController *enrollVC = [[EnrollMainViewController alloc]init];
    [self.navigationController pushViewController:enrollVC animated:YES];
}

/**
 *  登录接口   1密码登录     2验证码登录
 */
-(void)userCodeLoginWith:(NSString *)state{
   [SVProgressHUD showWithStatus:@"正在登录"];
    NSDictionary *jsonDic =  @{
                               @"commonParam":@{
                                       @"appKey":@"bbl40c2n1uq5zcvcvz",
                                       @"appVersion":AppVersion,
                                       @"page":@0,
                                       @"pagesize":@16
                                       },
                               @"object":@{
                                   @"channelId":DeviceToken,@"channelType":@"1",
                                       @"code":self.UserPasswordTF.text,
                                       @"phone":self.UserAccountTF.text,
                                           @"state":state
                                       }
                               };
  
    NSString *sign = [ChangeParameterWithMD5 getMd5WithCommonParamDic:jsonDic[@"commonParam"] Object:jsonDic[@"object"]];
    
    NSDictionary *json = @{
                           @"commonParam":@{
                                   @"appKey":@"bbl40c2n1uq5zcvcvz",
                                   @"appVersion":AppVersion,
                                   @"page":@0,
                                   @"pagesize":@16,
                                   @"sign":sign
                                   },
                           @"object":@{
                                   @"channelId":DeviceToken,@"channelType":@"1",@"code":self.UserPasswordTF.text,@"phone":self.UserAccountTF.text,@"state":state
                                   }
                           };
    
     [BanNetRequest BanNetRequestURL:UserLogin JsonParameters:json finish:^(NSDictionary *dic) {
         BXLog(@"登录%@",dic);
     [SVProgressHUD dismiss];
         if ([dic[@"status"] isEqualToString:@"0000"]){
           
             /**
              *  已加入公司的成员保存个人信息
              */
#pragma 保存公司信息  返回最近登录的公司信息
             UserManager *manager = [UserManager shareInstance];
             /**
              "2"已注册未加入公司
              "3"已加入公司的会员
              "4"管理员
              */
             NSString *status = dic[@"data"][@"companyUserInfo"][@"status"];
             
             if ([status isEqualToString:@"2"]){
                 
              [manager.userInfo setValuesForKeysWithDictionary:dic[@"data"][@"companyUserInfo"][@"userInfoOut"]];
                 
                 /**
                  *  一种未加入公司 一种已经提交加入公司审核 在审核中
                  */
                 NSString *message = dic[@"data"][@"message"];
                 if ([message rangeOfString:@"请等待管理员审核"].location != NSNotFound) {
                     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                     [alert show];
                 }else{
                     UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle: UIAlertControllerStyleAlert];
                     
                     UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                         NoCompanyViewController *noCompanyVC = [[NoCompanyViewController alloc]init];
                         [self.navigationController pushViewController:noCompanyVC animated:YES];
                     }];
                     UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                         
                     }];
                     [alert addAction:sure];
                     [alert addAction:cancel];
                     [self presentViewController:alert animated:YES completion:nil];
                 }
                 
            }else if ([status isEqualToString:@"3"]){
                 //普员
                 manager.userRank = 2;
                [self saveUserInfo:dic[@"data"][@"companyUserInfo"][@"userInfoOut"] companyInfo:dic[@"data"][@"companyUserInfo"][@"companyInfoOut"] companyId:dic[@"data"][@"companyUserInfo"][@"companyInfoOut"][@"companyId"]  token:dic[@"data"][@"token"]];
                 
             }else{
                 // 管理员
                 manager.userRank = 0;
                [self saveUserInfo:dic[@"data"][@"companyUserInfo"][@"userInfoOut"] companyInfo:dic[@"data"][@"companyUserInfo"][@"companyInfoOut"] companyId:dic[@"data"][@"companyUserInfo"][@"companyInfoOut"][@"companyId"]  token:dic[@"data"][@"token"]];
                 
             }
         
         }else if ([dic[@"status"] isEqualToString:@"9999"]){
             Alert(@"未知异常");
         }else{
             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:dic[@"message"] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
             [alert show];
         }
         
     } error:^(NSError *error) {
          [SVProgressHUD dismiss]; 
         Alert(@"登录失败");
     }];

}

/**
 *  获取验证码接口
 *
 */
-(void)getCode{
    [SVProgressHUD showWithStatus:@"正在获取验证码"];
    
    NSDictionary *jsonDic = @{
                              @"commonParam":@{
                                      @"appVersion":AppVersion,
                                      @"appKey":@"bbl40c2n1uq5zcvcvz",
                                      @"orgId":@"0",
                                      @"originatorId":@12,
                                      @"page": @0,
                                      @"pagesize": @4,
                                      },
                              @"object": @{
                                      @"phone":self.UserAccountTF.text
                                      }
                              };
    
    NSString *sign = [ChangeParameterWithMD5 getMd5WithCommonParamDic:jsonDic[@"commonParam"] Object:jsonDic[@"object"]];
    
    NSDictionary *json = @{
                           @"commonParam":@{
                                   @"appVersion":AppVersion,
                                   @"appKey":@"bbl40c2n1uq5zcvcvz",
                                   @"orgId":@"0",
                                   @"originatorId":@12,
                                   @"page": @0,
                                   @"pagesize": @4,
                                   @"sign":sign
                                   },
                           @"object": @{
                                   @"phone":self.UserAccountTF.text
                                   }
                           };
    [BanNetRequest BanNetRequestURL:SendCode JsonParameters:json finish:^(NSDictionary *dic) {
        NSLog(@"%@",dic[@"message"]);
        [SVProgressHUD dismiss];
        if ([dic[@"status"] isEqualToString:@"1010"]) {
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请核对手机号之后，重新获取验证码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
        }else if([dic[@"status"] isEqualToString:@"1015"]){
            [SVProgressHUD dismiss];
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请先输入手机号" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
        }else if ([dic[@"status"] isEqualToString:@"0000"]) {
            
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"消息" message:@"验证码已发送到您的手机，请注意查收" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
            
            _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeChangeNum) userInfo:nil repeats:YES];
            [_timer fire];
           forgetCodeBtn.enabled = NO;
            
        }else{
            UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请核对手机号之后，重新获取验证码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
        }
        
    } error:^(NSError *error) {
        NSLog(@"错误");
        [SVProgressHUD dismiss];
        UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"消息" message:@"请检查网络，重新尝试" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alertview show];
    }];
}



/**
 *  会员 管理员成功登录
 */
-(void)loginSuccess{
    BXTabBarController *mainVC = [[BXTabBarController alloc]init];
    LeftViewController *left = [[LeftViewController alloc]init];
    RootViewController *root = [[RootViewController alloc]initWithContentViewController:mainVC leftMenuViewController:left rightMenuViewController:nil];
    [self presentViewController:root animated:YES completion:nil];
}
/**
 *  保存用户信息 和token
 */
-(void)saveUserInfo:(NSDictionary*)userInfoDic companyInfo:(NSDictionary*)companyInfoDic companyId:(NSString*)companyId token:(NSString*)token{
    
    UserManager *manager = [UserManager shareInstance];
    
    /**
     *  保存个人信息 公司信息 以及token
     */
    if (userInfoDic!=nil) {
        [manager.userInfo setValuesForKeysWithDictionary:userInfoDic];
    }
    
    if (companyInfoDic!=nil) {
        [manager.companyInfo setValuesForKeysWithDictionary:companyInfoDic];
    }
    
    [manager handleAfterLoginSuccess:_UserAccountTF.text password:_UserPasswordTF.text companyId:companyId  token:token];
    
    if (companyId.length!=0) {
        [self loginSuccess];
    }
  
}

-(void)viewWillAppear:(BOOL)animated{
    [self.navigationController.navigationBar setHidden:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
